package org.company.earth.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class MyServerSocket extends Thread {
	
	public static void main(String[] args) throws IOException {
		MyServerSocket.startup();
	}
	private static ServerSocket server = null;
	private Socket socket = null;
	
	public MyServerSocket(Socket socket) {
		this.socket = socket;
	}
	
	public static void startup() throws IOException {
		SocketAddress endpoint = new InetSocketAddress(InetAddress.getLocalHost(), 8989);
		server = new ServerSocket();
		server.bind(endpoint);
		MyServerSocket serverSocket = null;
		Socket socket = null;
		try{
			while((socket = server.accept()) != null) {
				serverSocket = new MyServerSocket(socket);
				serverSocket.start();
			}
		}finally{
			server.close();
		}
	}
	
	public void run() {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String buffer = null;
			while((buffer = in.readLine()) != null) {
				if("shutdown".equalsIgnoreCase(buffer)) {
					break;
				}
				System.out.println(buffer);
			}
			in.close();
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
